<template>
  <div class="post-list-container">
    <div class="header-actions">
      <h1>宠物论坛</h1>
      <el-button type="primary" icon="el-icon-plus" @click="$router.push('/main/forum/create')">发布帖子</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入帖子标题"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类">
            <el-option label="养宠经验" value="EXPERIENCE"></el-option>
            <el-option label="宠物健康" value="HEALTH"></el-option>
            <el-option label="宠物趣事" value="FUNNY"></el-option>
            <el-option label="其他" value="OTHER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading-spinner></el-loading-spinner>
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <el-empty v-else-if="!postList.length" description="暂无帖子"></el-empty>

    <!-- 帖子列表 -->
    <template v-else>
      <el-card v-for="post in postList" :key="post.id" class="post-card" @click.native="viewDetail(post.id)">
        <div class="post-header">
          <div class="user-info">
            <el-avatar :src="post.userAvatar" :size="40">{{ post.username ? post.username.charAt(0) : 'U' }}</el-avatar>
            <div class="user-meta">
              <span class="username">{{ post.username || '未知用户' }}</span>
              <span class="post-time">{{ post.createTime }}</span>
            </div>
          </div>
          <el-tag size="small">{{ getCategoryText(post.category) }}</el-tag>
        </div>
        <div class="post-content">
          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-summary">{{ post.content }}</p>
        </div>
        <div class="post-footer">
          <div class="post-stats">
            <span class="stat-item">
              <i class="el-icon-view"></i>
              {{ post.viewCount || 0 }}
            </span>
            <span class="stat-item">
              <i class="el-icon-chat-dot-round"></i>
              {{ post.comments || 0 }}
            </span>
            <span class="stat-item" @click.stop="handleLike(post)">
              <i :class="['el-icon-star-off', { 'liked': post.liked }]" :style="{ color: post.liked ? '#409EFF' : '#909399' }"></i>
              {{ post.likes || 0 }}
            </span>
          </div>
          <div class="post-actions" v-if="userInfo && userInfo.id === post.userId">
            <el-button type="text" size="small" @click.stop="handleEdit(post.id)">编辑</el-button>
            <el-button type="text" size="small" class="danger" @click.stop="handleDelete(post)">删除</el-button>
          </div>
        </div>
      </el-card>
    </template>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getPostList, deletePost, likePost, unlikePost } from '@/api/post'
import { mapState } from 'vuex'

export default {
  name: 'PostList',
  data() {
    return {
      searchForm: {
        title: '',
        category: ''
      },
      postList: [],
      page: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      loading: false
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  methods: {
    // 获取帖子列表
    async fetchPostList() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize
        }
        const response = await getPostList(params)
        if (response.code === 200 && response.data) {
          this.postList = response.data.list || []
          this.total = response.data.total || 0
          this.page.pageNum = response.data.pageNum || 1
          this.page.pageSize = response.data.pageSize || 10
          
          // 处理用户头像URL和时间格式
          this.postList = this.postList.map(post => ({
            ...post,
            userAvatar: post.userAvatar || '/uploads/avatars/default.jpg',
            createTime: this.formatTime(post.createTime)
          }))
        } else {
          this.$message.error('获取帖子列表失败：' + (response.message || '未知错误'))
        }
      } catch (error) {
        console.error('获取帖子列表失败:', error)
        this.$message.error('获取帖子列表失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    // 搜索
    handleSearch() {
      this.page.pageNum = 1
      this.fetchPostList()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        title: '',
        category: ''
      }
      this.handleSearch()
    },
    // 查看详情
    viewDetail(id) {
      this.$router.push(`/main/forum/${id}`)
    },
    // 编辑帖子
    handleEdit(id) {
      this.$router.push(`/main/forum/${id}/edit`)
    },
    // 删除帖子
    handleDelete(post) {
      this.$confirm('确认删除该帖子吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePost(post.id).then(() => {
          this.$message.success('删除成功')
          this.fetchPostList()
        })
      }).catch(() => {})
    },
    // 点赞/取消点赞
    handleLike(post) {
      if (!this.userInfo) {
        this.$message.warning('请先登录')
        return
      }
      
      const request = post.liked ? unlikePost : likePost
      request(post.id)
        .then(response => {
          // 更新帖子的点赞状态
          this.$set(post, 'liked', !post.liked)
          this.$set(post, 'likes', post.liked ? (post.likes || 0) + 1 : (post.likes || 0) - 1)
          this.$message.success(post.liked ? '收藏成功' : '取消收藏成功')
        })
        .catch(error => {
          console.error('操作失败:', error)
          this.$message.error('操作失败')
        })
    },
    // 获取分类文本
    getCategoryText(category) {
      const categoryMap = {
        'EXPERIENCE': '养宠经验',
        'HEALTH': '宠物健康',
        'FUNNY': '宠物趣事',
        'OTHER': '其他'
      }
      return categoryMap[category] || '其他'
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchPostList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.fetchPostList()
    }
  },
  created() {
    this.fetchPostList()
  }
}
</script>

<style lang="scss" scoped>
.post-list-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .post-card {
    margin-bottom: 20px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    }

    .post-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .user-info {
        display: flex;
        align-items: center;

        .user-meta {
          margin-left: 10px;
          display: flex;
          flex-direction: column;

          .username {
            font-size: 14px;
            color: #303133;
            margin-bottom: 2px;
          }

          .post-time {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    .post-content {
      .post-title {
        margin: 0;
        margin-bottom: 10px;
        font-size: 16px;
        color: #303133;
      }

      .post-summary {
        margin: 0;
        color: #606266;
        font-size: 14px;
        line-height: 1.6;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }

    .post-footer {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-top: 1px solid #EBEEF5;
      padding-top: 15px;

      .post-stats {
        .stat-item {
          margin-right: 20px;
          color: #909399;
          font-size: 13px;
          cursor: pointer;

          i {
            margin-right: 4px;
          }

          i.liked {
            color: #409EFF;
          }

          &:hover {
            color: #409EFF;
          }
        }
      }

      .post-actions {
        .el-button {
          padding: 0 10px;
        }

        .danger {
          color: #F56C6C;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
  }
}
</style> 